const db = require("@/db/mysql");
const PublicModel = require("../../common/public.model");
const time = () => {
	const now = new Date();
	const date = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map(i => (i < 10 ? "0" + i : i)).join("-");
	const time = [now.getHours(), now.getMinutes(), now.getSeconds()].map(i => (i < 10 ? "0" + i : i)).join(":");
	return `${date} ${time}`;
};

class FileModel extends PublicModel {
	// 上传文件
	uploadFile({ id, name, path, suffix, original_name, size, storage_type }) {
        return this.create({
            table: 'file_files',
            data: {
                id, name, path, suffix, original_name, size, storage_type
            },
            result: true
        })
	}

	// 根据id-查询文件
	getFileById({ id }) {
		return db.query(`
      SELECT id, name, path, suffix, original_name
        , size, create_time
      FROM file_files
      WHERE is_delete = 0
        AND id = '${id}'
    `);
	}

	/**
     * 绑定业务
     * @param {*} param0 
     * @param {string[]} param0.files 附件id列表
     * @param {string} param0.business_id 业务id
     * @param {string} param0.business_type 业务类型
     * @param {string} param0.file_category 业务分类
     * @param {string} param0.extra_data 扩展数据
     * @param {string} param0.file_purpose 文件用途
     * @param {string} param0.result 是否返回查询结果
     * @returns 
     */
	bidBizFile({ files, business_id, business_type, file_category, extra_data, file_purpose, result }) {
        files = Array.isArray(files) ? files : [];
        files = files.map(id => {
            return {
                file_id: id,
                business_id: business_id,
                business_type: business_type,
                file_category: file_category,
                extra_data: extra_data ? JSON.stringify(extra_data) : null,
                file_purpose: file_purpose,
            }
        });
        return this.createMultiple({
            table: 'file_bindings',
            data: files,
            result: result
        })
	}

	// 业务查询文件列表
	queryFileByBiz({ bizId }) {
		return db.query(`
      SELECT 
        bf.id,
        bf.remark,
        fs.id as fileId, 
        fs.name, 
        fs.path, 
        fs.suffix, 
        fs.size,
        fs.original_name, 
        fs.create_user, 
        fs.create_time
      FROM 
        file_bindings as bf 
        LEFT JOIN file_files as fs ON bf.file_id = fs.id 
      WHERE 
        bf.biz_id = '${bizId}' 
        AND fs.is_delete = 0 
    `);
	}

	// 删除文件
    deleteFile({ id }) {
        return this.deleteById({ table: 'file_files', id: id });
	}

	// 设置MD5hash
	setFileMD5Hash({ id, hash }) {
		return db.query(`UPDATE file_files SET md5_hash = '${hash}' WHERE id = '${id}'`);
	}

	// 设置附件绑定业务id
	setFileBindBusiness(ids) {
		const idStr = `${ids.map(id => "'" + id + "'").join(", ")}`;
		return db.query(`UPDATE file_files SET is_lock = 1 WHERE id IN (${idStr})`);
	}
}

module.exports = new FileModel();
